package cc.facesign.admin.listener;

import cc.facesign.admin.bean.xls.AddDeptUserXls;
import cc.facesign.admin.dao.xls.XlsDao;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * xls向部门导入数据
 */

@Slf4j
public class DeptUserXlsListener implements ReadListener<AddDeptUserXls> {

    // 有异常的用户信息
    private List<AddDeptUserXls> errs;

    public List<AddDeptUserXls> getErrs() {
        return errs;
    }

    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<AddDeptUserXls> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private XlsDao xlsDao;

    private List<MultipartFile> pics;

    private String deptId;


    public DeptUserXlsListener(XlsDao xlsDao, List<MultipartFile> pics, String deptId) {
        errs = new ArrayList<>();
        this.xlsDao = xlsDao;
        this.pics = pics;
        this.deptId = deptId;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     */
    @Override
    public void invoke(AddDeptUserXls data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<AddDeptUserXls> ret = null;
        try {
            ret = xlsDao.saveForAddUserInDept(cachedDataList, pics, deptId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        errs.addAll(ret);
        log.info("存储数据库成功！");
    }
}